//
//  CYImagePlayView.m
//  aLiPay
//
//  Created by ccy on 2017/5/19.
//  Copyright © 2017年 ccy. All rights reserved.
//

#import "CYImagePlayView.h"
#//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND

//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"
#import "CYImageCell.h"
#import "CYpageView.h"
#import "YYWebImage.h"
#import "UIImageView+WebCache.h"
#import "UIColor+CY_RGB.h"
#import "UIColor+CYHexColor.h"
@interface CYImagePlayView ()<UICollectionViewDataSource,UICollectionViewDelegate>


@property(nonatomic,weak) UICollectionView  *imageCollectionView;
@property(nonatomic,weak) UIPageControl  *pageControl;
@property(nonatomic,strong) NSTimer *time;
/**
 自定义分页符
 */
@property(nonatomic,strong) CYpageView *pageView;

@end


static NSString *ID_cell = @"cell";


@implementation CYImagePlayView


//#pragma mark
//#pragma mark - 懒加载
//-(NSArray *)imageArray
//{
//    if (_imageArray == nil)
//    {
//        NSMutableArray *tempArray = [NSMutableArray array];
//        for (int i = 1 ; i < 6; i++) {
//            
//            [tempArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"ad%d",i]]];
//        }
//        _imageArray =tempArray.copy;
//    }
//    return _imageArray;
//}



-(void)setImageArray:(NSArray *)imageArray
{
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSString *imageURL in imageArray) {
        [arrM addObject:imageURL];
    }
    _imageArray = arrM.copy;
    if (_imageArray.count > 0) {
        [self.imageCollectionView reloadData];
        [self setupPageControl];
        [self openTime];

    }
   
}


#pragma mark
#pragma mark - 实例化
-(instancetype)initWithFrame:(CGRect)frame andActivity_mobileArray:(NSArray *)activity_mobileArray
{
    if (self = [super initWithFrame:frame]) {
        self.imageArray = [NSArray new];
        self.imageArray = activity_mobileArray;
        
        [self setupUI];
    }
    return self;
}

-(void)setupUI
{
    [self setupCollcetionView];
}

-(void)openTime
{
    self.time = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(timeOut) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.time forMode:NSRunLoopCommonModes];
}


#pragma mark
#pragma mark - 搭建界面
-(void)setupCollcetionView
{

    
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
    //实例化一个collection
    UICollectionView *imageCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowlayout];
    //设置数据源代理
    self.imageCollectionView = imageCollectionView;
    imageCollectionView.dataSource = self;
    imageCollectionView.delegate = self;//self.frame.size.height
    flowlayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 150);
    //注册
    [imageCollectionView registerClass:[CYImageCell class] forCellWithReuseIdentifier:ID_cell];
    
    flowlayout.minimumLineSpacing = 0;
    flowlayout.minimumInteritemSpacing = 0;
    
    //设置横向滚动
    flowlayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //取消滚动条
    imageCollectionView.showsHorizontalScrollIndicator = NO;
    //设置设置分页效果
    imageCollectionView.pagingEnabled = YES;
    //添加
    [self addSubview:imageCollectionView];
    //设置约束
    imageCollectionView.backgroundColor = [UIColor whiteColor];
    [imageCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
//    
//    imageCollectionView.frame = CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width , 150);
   
}

#pragma mark
#pragma mark - 实现数据源方法
//多少组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//多少行
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArray.count * 2;
}
//每组显示的单元格
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //注册
    CYImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID_cell forIndexPath:indexPath];
    //传递数据
  NSInteger newIndex =  indexPath.row % self.imageArray.count;

    [cell.imageView yy_setImageWithURL:[NSURL URLWithString:self.imageArray[newIndex]] placeholder:[UIImage imageNamed:@"v2_placeholder_full_size"]];
    //返回
    return cell;
}
#pragma mark
#pragma mark - 分页符设置
-(void)setupPageControl
{
    UIPageControl *pageControl = [[UIPageControl alloc]init];
    pageControl.numberOfPages = self.imageArray.count;
    self.pageControl = pageControl;
    //设置颜色
    pageControl.currentPageIndicatorTintColor = [UIColor ColorWithHex:0xFFD547];
    pageControl.pageIndicatorTintColor = [UIColor ColorWithHex:0xEEEDED];
    //添加
    [self addSubview:pageControl];
    //设置约束
    [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.equalTo(self);
        make.trailing.equalTo(self).offset(-10);
        make.bottom.equalTo(self.mas_bottom).offset(5);
    }];
    
    #pragma mark - 自定义分页指示器
//    CYpageView *pageView = [CYpageView pageView];
////    [[NSBundle mainBundle]loadNibNamed:@"CYpageView" owner:nil options:nil].lastObject;
//    [self addSubview:pageView];
//    pageView.sumLabel.text = [NSString stringWithFormat:@"/%ld",self.imageArray.count];
//    self.pageView = pageView;
//    [pageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.trailing.offset(-10);
//        make.width.equalTo(65);
//        make.height.equalTo(20);
//        make.bottom.equalTo(self.mas_bottom).offset(-5);
//    }];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
//    NSLog(@"456789");
#pragma mark
#pragma mark - 程序一开始滚动到第1组第0个
    [self.imageCollectionView setContentOffset:CGPointMake( self.imageCollectionView.frame.size.width * self.imageArray.count ,0)];
}


#pragma mark
#pragma mark - 实现代理方法

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self calculateAndJumpWithScrollView:scrollView];
}

//手指滑动时暂停计时
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.time.fireDate = [NSDate distantFuture];
}

//手指离开开始计时
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    self.time.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
}



#pragma mark
#pragma mark - 计时到了
-(void)timeOut
{
    [self.imageCollectionView setContentOffset: CGPointMake(self.imageCollectionView.contentOffset.x + self.imageCollectionView.frame.size.width,0) animated:YES];
    
//    CATransition *transition = [[CATransition alloc]init];
//    #warning 一定要写在定时器中结束后方法调用中
//    transition.type = @"cube";
//    transition.subtype = @"fromRight";
//    transition.duration = 1;
//    [self.imageCollectionView.layer addAnimation:transition forKey:nil];
}



//自动滑动时计算contentoffset
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    
    [self calculateAndJumpWithScrollView:scrollView];
}


//计算页码和是否需要跳转
-(void)calculateAndJumpWithScrollView:(UIScrollView *)scrollView
{
    NSInteger index =  scrollView.contentOffset.x / scrollView.frame.size.width;
    NSInteger newIndex = index % self.imageArray.count;
    self.pageControl.currentPage = newIndex;
//    self.pageView.selIndex = newIndex;
    self.pageView.indeexLabel.text = [NSString stringWithFormat:@"%ld",newIndex + 1];
    NSInteger count = [self.imageCollectionView numberOfItemsInSection:0];
    //   NSLog(@"%ld---%ld",index,count);
    
    if (index == count - 1)
    {
        //如果到了第1组第4张就返回第一组第四张
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.imageArray.count - 1 inSection:0];
        [self.imageCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    }
    else if(index == 0)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.imageArray.count  inSection:0];
        [self.imageCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
    }
}

//对象释放时,计时器无效化
-(void)dealloc
{
    [self.time invalidate];
}
@end
















